﻿"use strict";
var util = require('util');
var sqlite3 = require('sqlite3').verbose();

var db_define_str = null;
var db_define_obj = null;
var db_info = null;
var db_map = null;

function dbmap_cache(tablename, info) {
    if (db_map == null)
        return null;
    let dbtable = db_map.get(tablename);
    if (dbtable == null)
        return null;
    else
        return dbtable[info];
}


function judge_insert(type) {
    var strtype = "";
    strtype += type;
    var uptype = strtype.toUpperCase();
    if (uptype.indexOf("AUTOINCREMENT") > 0) {
        return false;
    }
    if (uptype.indexOf("DATETIME") > 0) {
        return false;
    }
    return true;
}
// 创建表的sql语句
function sql_create(tablename, fields) {
    var ret = "create table if not exists ";
    ret += tablename;
    ret +="(";
    for (var key in fields) {
        ret += "[";
        ret += key;
        ret += "] ";

        var t = fields[key].type;
        if (t == undefined) {
//          console.log("key's type not defined");
            t = "TEXT";
        }
        ret += t;
        ret += ",";
    }
    ret = ret.substr(0, ret.length - 1);
    ret += ")";
    return ret;
}
// 表中字段的插入sql
function sql_insert(tablename, fields, fieldnum) {
    var nfield = parseInt(fieldnum);
    var ret = "insert into ";
    ret +=tablename;
    ret +="(";
    var values = "values(";
    for (var key in fields) {
        if (judge_insert(fields[key].type) == true) {
            ret += key;
            ret += ",";
            values += "?"
            values += ","
        }
    }
    ret = ret.substr(0, ret.length - 1);
    values = values.substr(0, values.length - 1);
    ret += ")";
    values += ")";
    ret += values;
    return ret;
}
// 删除表的sql
function sql_delete_table(tablename){
    var ret = "drop table ";
    ret += tablename;
    return ret;
}
// 删除表中数据的sql
function sql_delete(tablename) {
    var ret = "delete from ";
    ret += tablename;
    ret += " where id = ?";
    //ret += " where id in ? ";
    return ret;
}
// 查找
function sql_select_mul(tablename) {
    var ret = "select * from ";
    ret += tablename;
    ret += " where id in (?)";
    //ret += " where id in ? ";
    return ret;
}
// 删除
function sql_delete_mul(tablename) {
    var ret = "delete from ";
    ret += tablename;
    ret += " where id in (?)";
    //ret += " where id in ? ";
    return ret;
}
function sql_clear(tablename, wherecondition) {
    var ret = "delete from ";
    ret += tablename;
    ret += wherecondition;
    return ret;
}
function sql_update(tablename, fields, fieldnum) {
    //let fields = 
    var ret = "update ";
    ret += tablename;
    var i = 0;
    ret += " set ";
    for (var key in fields) {
        i++;
        var strtype = "";
        strtype += fields[key].type;
        if (judge_insert(strtype) == true) {
            ret += key;
            ret += "="
            ret += " ? "
            if (i != fieldnum)
                ret += ",";
        }
        //var uptype = strtype.toUpperCase();
        //if (uptype.indexOf("AUTOINCREMENT") > 0) {
        //    continue;
        //}
    }
    ret += " where id = ?";
    //ret += id;
    return ret;
}


function handle_table_leftjoin(table) {
    var sql = " select "
    var lfields = table.left.fields;
    var ltablename = table.left.name;
    var lalias = table.left.alias;
    var rtablename = table.right.name;
    var ralias = table.right.alias;
    sql += lfields;
    sql += ",";
    var rfields = table.right.fields;
    sql += rfields;
    sql += " from ";
    sql += ltablename;
    sql += " ";
    sql += lalias;
    sql += " left join ";
    sql += rtablename;
    sql += " ";
    sql += ralias;
    return sql;
}
function field_analyse(f, alias) {
    var str = "";
    str += f;
    //console.log(str);
    var fieldx = str.split(',');
    var slen = fieldx.length;
    var out = "";
    var si = 0;
    fieldx.map(function (item) {
        var text = item.trim();
        //console.log(text, text.length);
        out += alias + "." + text + " " + text;
        si++;
        if (si < slen)
            out += ","
    });
    // console.log(out);
    return out;
}


function handle_table_leftjoin2(table) {
    var sql = " select "

    var lfields = field_analyse(table.left.fields, "a");
    var ltablename = table.left.name;
    var rtablename = table.right.name;

    sql += lfields;
    sql += ",";
    var rfields = field_analyse(table.right.fields, "b");
    sql += rfields;
    sql += " from ";
    sql += ltablename;
    sql += " a";
    sql += " left join ";
    sql += rtablename;
    sql += " b";
    return sql;
}

function map_create2() {
    map_create(db_define_str);
}
// 创建表创建视图
function map_create(define) {
    console.log("init start");
    if (db_map == null) {
        db_map = new Map();
    }
    var table_field = null;
    var table_view = null;
    if (define == null) {
        console.log("no define ,error!");
		return ;
        //table_field = db_define.table_field;
        //table_view = db_define.table_view;
    }
    else {
        table_field = define.table_field;
        table_view = define.table_view;
    }
    if (table_field != null) {
        for (var i = 0; i < table_field.length; i++) {
            let name = table_field[i].tablename;
            let fields = table_field[i].fields;
            let fieldnum = table_field[i].fieldnum;
            let str_create = sql_create(name, fields);
            let str_insert = sql_insert(name, fields, fieldnum);
            let str_update = sql_update(name, fields, fieldnum);
            let str_delete = sql_delete(name);
            let str_delete_mul = sql_delete_mul(name);
            //let str_select = sql_select(tablename);
            var info = {};
            info["fields"] = fields;//table_field[i].fields;
            info["fieldnum"] = fieldnum;
            info["create"] = str_create;
            info["insert"] = str_insert;
            info["update"] = str_update;
            info["delete"] = str_delete;
            info["delete_mul"] = str_delete_mul;
            db_map.set(name, info);
            //创建所有的表以及表中的字段
            db_create(str_create, name);
        }
    }
    if (table_view != null) {
        for (var i = 0; i < table_view.length; i++) {
            if (table_view[i].type == "left") {
                var sql = "";
                if (table_view[i].table.left.alias != undefined) {
                    sql = handle_table_leftjoin(table_view[i].table)
                }
                else {
                    sql = handle_table_leftjoin2(table_view[i].table);
                }

                sql += " ";
                sql += table_view[i].where;
                let viewname = table_view[i].tablename;
                let view = "create view if not exists " + viewname + " as ";

                sql = view + sql;
                //console.log(sql);
                db_create(sql, viewname);
            }
            else if (table_view[i].type == "group") {
                let viewname = table_view[i].tablename;
                var sql = "create view if not exists " + table_view[i].tablename;
                sql += " as ";
                sql += table_view[i].sql;
                db_create(sql, viewname);
            }
        }
    }
}

function db_create(sql,tablename) {
    db_info.run(sql,log_prepare(tablename));
}
function log_prepare(tablename) {
   // console.log("prepare table %s is ok", tablename);
}
function db_info_init2(define, dbname) {
    db_define_str = define;
    db_info = new sqlite3.Database(dbname, map_create2);
}
// 闵亚楠 start：2017.9.11  
function db_update_name(){
    // console.log('ok');
}
// 操作指定数据库
function db_info_init3(dbname){
   db_info = new sqlite3.Database(dbname,db_update_name);
}
// 查询该数据库下的所有表
function db_edit_get_tables(cb){
   var sql = 'select name from sqlite_master where type = "table" and tbl_name != "sqlite_sequence" order by name';
   if(db_info == null){
        console.log("null error");
        return ;
    }
    db_info.all(sql,function(err,rows){
        if (err) {
            return;
        }
        if (cb != null) {
            cb(1,rows);
        }
    });
}
// 查询该表下的所有字段
function db_edit_get_fields(tablename,cb){
   var sql = "pragma table_info(";
   sql += tablename+")";
   if(db_info == null){
        console.log("null error");
        return ;
    }
    db_info.all(sql,function(err,rows){
        if (err) {
            return;
        }
        if (cb != null) {
            cb(1,rows);
        }
    });
}
// 添加表
function db_edit_create_table(define,cb){
        db_define_obj = define;
        if (db_define_obj != null) {
            let name = db_define_obj.tablename;
            let fields = db_define_obj.fields;
            let str_create = sql_create(name, fields);
            if(db_info == null){
                console.log("null error");
                return ;
            }
            db_info.run(str_create,function(err){
                if (cb != null) {
                    cb(1,'ok');
                }
            });
        }
}
// 删除表
function db_edit_delete_table(tablename,cb){
    let sql_delete = sql_delete_table(tablename);
    if(db_info == null){
        console.log("null error");
        return ;
    }
    db_info.run(sql_delete,function(err){
        if (cb != null) {
            cb(1,'ok');
        }
    });
}
// 在表中添加一个字段
function db_edit_add_field(tablename,fieldname,type,cb){
   var sql = "alter table ";
   sql += tablename;
   sql += " add " + fieldname + " "+type;
   if(db_info == null){
        console.log("null error");
        return ;
    }
    db_info.run(sql,function(err){
        if (cb != null) {
            cb(1,'ok');
        }
    });
}


// 闵亚楠 end

//data为json对象     var data = { author: "qianbo", projectid: 111, imgid: "101", info: "test111" };
function db_info_insert(tablename, data,cb) {
    var sql = dbmap_cache(tablename, "insert");
    if (sql == null) {
        console.log("insert sql is null ,maybe db is not ready, error!");
        return;
    }
    var stmt = db_info.prepare(sql);
    var fields = dbmap_cache(tablename, "fields");
    var data_ = [];
    for (var key in fields) {
        if (judge_insert(fields[key].type) == true) {
            data_.push(data[key]);
        }
    }
   
    stmt.run(data_, function (error) {
        if (error) {
            console.log(error);
            if(cb!=null)
                cb(-1, error);
            return;
        }
        else {
            if (cb != null){
                var insertId = stmt.lastID;//获取自动生成的id
                cb(1, insertId);
            }
        }
    });
    stmt.finalize();

}
function db_info_insert_norepeat(tablename, index_array, data, cb) {
    var sql = "select count(*) total from %s %s ";
    var where= " where 1=1 ";
    //获取所有字段    
    for(var i =0;i<index_array.length;i++){
        var wx = '';
        var fields = dbmap_cache(tablename, "fields");
        var index = index_array[i];
        if (fields[index] == null) {
            console.log("error db_info_insert_some() key null");
            return;
        }        
        wx += " and ";
        wx += index ;
        wx += " = ";
        wx += '"' + data[index] +'"';
        where += wx;
    }

    sql  = util.format(sql,tablename,where);
    // console.log(sql);
    db_info.get(sql, function (err, row) {
        if (err) {
            console.log("db_info_insert_some() error! the sql is %s", sql);
            return;
        }
        if(row.total > 0){
            var error = util.format("%s %s 数据不能重复", tablename, index);
            // console.log(error);
            if (cb != null) {
               cb(-2, "重复");
            }
        }
        else {
            db_info_insert_some2(tablename, data, cb);
        }
    });

}


function db_info_update(tablename, data, cb) {
    if (data.id == null) {
        console.log("id is null, please do not kidding me");
        return;
    }

    var sql = dbmap_cache(tablename, "update");

    if (sql == null) {
        console.log("update sql is null, error!");
        return;
    }
    var stmt = db_info.prepare(sql);
    var fields = dbmap_cache(tablename, "fields");
    var data_ = [];//["qianbo1", 11, "10", "test"];
    for (var key in fields) {
        if (judge_insert(fields[key].type) == true) {
            data_.push(data[key]);
        }
    }
    data_.push(data.id);
    stmt.run(data_, function (error) {
        if (error) {
            consle.log(error);
            if(cb!=null)
                cb(-1, error);
            return;
        }
        else {
            if(cb!=null)
                cb(1,tablename);
        }
    });
    stmt.finalize();
}


function db_info_update_bysql(sql, cb) {
    var stmt = db_info.prepare(sql);
    stmt.run(function (error) {
        if (error && cb != null) {
            console.log(error);
            cb(-1, error);
            return;
        }
        else {
            if (cb != null)
                cb(1, "");
        }
    });
    stmt.finalize();
}
function db_info_delete_by_key(tablename, key, value, cb) {
    if (key == null || value == null) {
        console.log("key or value is null, please do not kidding me");
        return;
    }
    var sql = util.format("delete from %s where %s=?",tablename, key);

    var stmt = db_info.prepare(sql);
    stmt.run(value, function (error) {
        if (error && cb != null) {
            cb(-1, error);
            return;
        }
        else {
            if (cb != null)
                cb(1, tablename);
            stmt.finalize();
        }
    });
}

function db_info_delete_bysql(sql,cb){
    var stmt = db_info.prepare(sql);
    stmt.run(function (error) {
        if (error && cb != null) {
            console.log(error);
            cb(-1, error);
            return;
        }
        else {
            if(cb!=null)
                cb(1, "");
        }
    });
    stmt.finalize();
}

function db_info_delete(tablename, data,cb) {
    if (data == null)
        return;
    if (data.id == null) {
        console.log("id is null, please do not kidding me");
        return;
    }
    var sql = dbmap_cache(tablename, "delete");
    if (sql == null) {
        console.log("update sql is null, error!");
        return;
    }
    var stmt = db_info.prepare(sql);
    stmt.run(data.id, function (error) {
        if (error && cb!=null) {
            cb(-1, error);
            return;
        }
        else {
            if(cb!=null)
                cb(1, tablename);
        }
    });
    stmt.finalize();
}
function db_info_delete_mul(tablename, data,cb) {
    // console.log(data);
    if (data == null) {
        return;
    }
    //[1,2,3,4]
    if (data.length == 0) {
        console.log("id.length is 0, please do not kidding me");
        return;
    }
    var str_del = "";
    for (let i = 0; i < data.length; i++) {
        str_del += data[i];
        if (i < data.length - 1)
            str_del += ",";
    }
    // console.log("delete:%s",str_del);

    var sql = util.format("delete from %s where id in (%s)",tablename,str_del)
    // dbmap_cache(tablename, "delete_mul");
    if (sql == null) {
        console.log("delete sql is null, error!");
        return;
    }
    //console.log("the delete_mul sql is %s", sql);
    var stmt = db_info.prepare(sql);
    stmt.run(function (error) {
        if (error && cb != null) {
            cb(-1, error);
            return;
        }
        else {
            if(cb!=null)
                cb(1, tablename);
        }
    });
    stmt.finalize();
}
function db_info_select_mul(tablename, data,cb) {
    // console.log(data);
    if (data == null) {
        return;
    }
    //[1,2,3,4]
    if (data.length == 0) {
        console.log("id.length is 0, please do not kidding me");
        return;
    }
    var str_sel = "";
    for (let i = 0; i < data.length; i++) {
        str_sel += data[i];
        if (i < data.length - 1)
            str_sel += ",";
    }
//  console.log("select:%s",str_sel);

    var sql = util.format("select * from %s where id in (%s)",tablename,str_sel)
    // dbmap_cache(tablename, "delete_mul");
//  console.log(sql);
    if (sql == null) {
        console.log("select sql is null, error!");
        return;
    }
    //console.log("the delete_mul sql is %s", sql);
    db_info_select_bysql(sql,cb);
}
//pagenumber 从第一页开始
//event 返回的事件名称
function db_info_read_page(tablename, pagesize, pagenumber, where, cb,event) {
    //计算有多少页
     var sql = "";
     if (where != null)
         sql = util.format("select count(*) as count from %s where %s", tablename,where);
     else
         sql = util.format("select count(*) as count from %s", tablename);

     db_info.get(sql, function (err, row) {
         if (err) {
             console.log("error select:sql is %s",sql);
             return;
         }
        var pagecount = (row.count - 1) / pagesize + 1;
        //console.log("the 页数 is %d,每页为%d", parseInt(pagecount), pagesize);

        var offset = pagesize * (pagenumber - 1);
        var sqlselect_ = "";
        var sqlselect = "";
        if (where != null) {
            sqlselect_ = "select * from %s where %s order by rowid desc limit %d offset %d ";
            sqlselect = util.format(sqlselect_, tablename, where, pagesize, offset);
        }
        else {

            sqlselect_ = "select * from %s order by rowid desc limit %d offset %d"
            sqlselect = util.format(sqlselect_, tablename, pagesize, offset);
        }

        //console.log(sqlselect);
        db_info.all(sqlselect, function (err, rows) {
            if (err) {
                console.log("db_info_read_page() error! the sql is %s", sqlselect);
                if (cb)
                    cb(null, 0, event);
                return;
            }
            if (cb) {
                //  var obj_json = JSON.parse(rows);
                //增加传回页数
                cb(rows, parseInt(row.count),parseInt(pagecount),event);
            }
        });
    });
}
//condition 包含order by group,不包含where
//body 为http协议中的body
function db_info_read_page2(tablename, pagesize, pagenumber, condition, cb) {
    //计算有多少页
    var sql = "";
    //var where = get_where(tablename, body);
    if (condition != null)
        sql = util.format("select count(*) as count from %s %s", tablename, condition);
    else
        sql = util.format("select count(*) as count from %s", tablename);
        db_info.get(sql, function (err, row) {
        if (err) {
            console.log("error select:sql is %s", sql);
            return;
        }
        var pagecount = (row.count - 1) / pagesize + 1;
        //console.log("the 页数 is %d,每页为%d", parseInt(pagecount), pagesize);
        var offset = pagesize * (pagenumber - 1);
        var sqlselect_ = "";
        var sqlselect = "";
        if (condition != null) {
            sqlselect_ = "select * from %s %s limit %d offset %d ";
            sqlselect = util.format(sqlselect_, tablename, condition, pagesize, offset);
        }
        else {
            sqlselect_ = "select * from %s order by rowid desc limit %d offset %d"
            sqlselect = util.format(sqlselect_, tablename, pagesize, offset);
        }

//      console.log(sqlselect);
        db_info.all(sqlselect, function (err, rows) {
           // console.log(sqlselect);
            if (err) {
                console.log("db_info_read_page() error! the sql is %s", sqlselect);
                if (cb)
                    cb(null,0, 0);
                return;
            }
            if (cb) {
                //  var obj_json = JSON.parse(rows);
                //增加传回页数
                cb(rows, parseInt(pagecount), parseInt(row.count));
            }
        });
    });
}
/*
 * fields 字段用逗号分开
 */
function db_info_read_page3(tablename,fields,pagesize, pagenumber, condition, cb) {
    //计算有多少页
    var sql = "";
    //var where = get_where(tablename, body);
    if (condition != null)
        sql = util.format("select count(*) as count from %s %s", tablename, condition);
    else
        sql = util.format("select count(*) as count from %s", tablename);
        db_info.get(sql, function (err, row) {
        if (err) {
            console.log("error select:sql is %s", sql);
            return;
        }
        var pagecount = (row.count - 1) / pagesize + 1;
        //console.log("the 页数 is %d,每页为%d", parseInt(pagecount), pagesize);
        var offset = pagesize * (pagenumber - 1);
        var sqlselect_ = "";
        var sqlselect = "";
        if (condition != null) {
            sqlselect_ = "select %s from %s %s limit %d offset %d ";
            sqlselect = util.format(sqlselect_,fields, tablename, condition, pagesize, offset);
        }
        else {
            sqlselect_ = "select %s from %s order by rowid desc limit %d offset %d";
            sqlselect = util.format(sqlselect_,fields, tablename, pagesize, offset);
        }

//      console.log(sqlselect);
        db_info.all(sqlselect, function (err, rows) {
           // console.log(sqlselect);
            if (err) {
                console.log("db_info_read_page() error! the sql is %s", sqlselect);
                if (cb)
                    cb(null,0, 0);
                return;
            }
            if (cb) {
                //  var obj_json = JSON.parse(rows);
                //增加传回页数
                cb(rows, parseInt(pagecount), parseInt(row.count));
            }
        });
    });
}
/*
 * fields 字段用逗号分开
 */
function db_info_read_page4(tablename,fields,pagesize, pagenumber, condition, cb,event) {
    //计算有多少页
    var sql = "";
    //var where = get_where(tablename, body);
    if (condition != null)
        sql = util.format("select count(*) as count from %s %s", tablename, condition);
    else
        sql = util.format("select count(*) as count from %s", tablename);
        db_info.get(sql, function (err, row) {
        if (err) {
            console.log("error select:sql is %s", sql);
            return;
        }
        var pagecount = (row.count - 1) / pagesize + 1;
        //console.log("the 页数 is %d,每页为%d", parseInt(pagecount), pagesize);
        var offset = pagesize * (pagenumber - 1);
        var sqlselect_ = "";
        var sqlselect = "";
        if (condition != null) {
            sqlselect_ = "select %s from %s %s limit %d offset %d ";
            sqlselect = util.format(sqlselect_,fields, tablename, condition, pagesize, offset);
        }
        else {
            sqlselect_ = "select %s from %s order by rowid desc limit %d offset %d";
            sqlselect = util.format(sqlselect_,fields, tablename, pagesize, offset);
        }

//      console.log(sqlselect);
        db_info.all(sqlselect, function (err, rows) {
           // console.log(sqlselect);
            if (err) {
                console.log("db_info_read_page() error! the sql is %s", sqlselect);
                if (cb)
                    cb(null,0, 0);
                return;
            }
            if (cb) {
                //  var obj_json = JSON.parse(rows);
                //增加传回页数
                cb(rows, parseInt(row.count),parseInt(pagecount),event);
            }
        });
    });
}
// 读取指定表的指定条件的数量
function db_info_read_count(tablename, where, cb) {
    //计算有多少页
     var sql = "";
     if (where != null)
         sql = util.format("select count(*) as count from %s where %s", tablename,where);
     else
         sql = util.format("select count(*) as count from %s", tablename);

     db_info.get(sql, function (err, row) {
         if (err) {
             console.log("error select:sql is %s",sql);
             return;
         }
         if (cb != null) {
            cb(1,row.count);
         }
    });
}
//从每个表中获取where数据
function get_where(tablename, body) {
    var where = " where 1=1 ";
    //从表中查找where的搜索
    var fields = dbmap_cache(tablename, "fields");
    var data_ = [];//["qianbo1", 11, "10", "test"];
    for (var key in fields) {
        if (judge_insert(fields[key].type) == true) {
            
            if (body[key] != null) {
                where += " and " + key + "='";
                where += body[key];
                wher += "'";
            }
        }
    }
    return where;
}



/*
//field     :字段数组
//condition :where或者group条件
//event     :事件名称
*/
function db_info_select_bysql(sql, cb) {
    var a = db_info.all(sql, function (err, rows) {
        if (err) {
            console.log("db_info_select_bysql()  error! the sql is %s", sql);
            cb(-1, err);
        }
        else{
            if (cb != null) {
                cb(1, rows);
            }
        }
    });
}
//只选取一行
function db_info_get_bysql(sql, cb) {
//	console.log(sql);
    var a = db_info.get(sql, function (err, row) {
        if (err) {
            console.log("db_info_get_bysql()  error! the sql is %s", sql);
            cb(-1, err);
            return;
        }
        if (cb != null) {
            cb(1, row);
        }
    });
}

function db_info_select(tablename, fields, condition, event, cb) {
    var strfield = "";
    //console.log(fields.length);
    for (var i = 0; i < fields.length; i++) {
        strfield += fields[i];
        if (i < (fields.length - 1)) {
            strfield += ","
        }
    }

    var select = "";
    if (condition != null)
        select = util.format("select %s from %s %s", strfield, tablename , condition);
    else
        select = util.format("select %s from %s", strfield, tablename);
    var a = db_info.all(select, function (err, rows) {
        //console.log(select);
        if (err) {
            console.log("db_info_select()  error! the sql is %s", select);
            return;
        }
        if (cb != null) {
            cb(rows,event);
        }
    });
}
function db_info_select2(tablename, fields, condition,cb) {
    var strfield = "";
    //console.log(fields.length);
    for (var i = 0; i < fields.length; i++) {
        strfield += fields[i];
        if (i < (fields.length - 1)) {
            strfield += ","
        }
    }
    var select = "";
    if (condition != null)
        select = util.format("select %s from %s %s", strfield, tablename , condition);
    else
        select = util.format("select %s from %s", strfield, tablename);
    var a = db_info.all(select, function (err, rows) {
        //console.log(select);
        if (err) {
            console.log("db_info_select2()  error! the sql is %s", select);
            if(cb!=null){
                cb(-1,err);    
            }
        }
        else {
            if(cb != null) 
                cb(1,rows);
        }
    });
}
//key 为主键
//data为要插入或者更新的数据,和db_info_insert不同
//db_info_update 根据所有预定义字段(db_define.js)插入，并更新所有字段
//db_info_update_some自己写字段插入，只插入一些字段
function db_info_update_some(tablename, key, data, cb) {
    // console.log("db_info_update_some",key, data);
    var keyvalue = data[key];
    if (data[key] == null) {
        if (cb!=null) {
            cb(0, null);
        }    
        console.log("db_info_update_some() key is null");
        return;
    }
    var sql = util.format("select count(*) as count from %s where %s ='%s' ", tablename, key, data[key]);
    //console.log(sql);

    db_info.get(sql, function (err, row) {
        if (err) {
            console.log(err);
            return;
        }
        if (row.count == 0) { //没有数据可以更新,可能被删除
            console.log("no data");
            if (cb!=null) {
                cb(0, null);
            }
            return;
        }
        //得到所有该表的列名
        var fields = dbmap_cache(tablename, "fields");
        var setvalue = "set ";
        var value = [];//插入的值
        for (var k in data) {
            if (k != key && fields[k] != null) { //不是主键 并且包含在表声明里
                setvalue += k;
                setvalue += "=?,"
                value.push(data[k]);
            }
        }
        if (value.length == 0) {
            console.log("no value set ,return");
            return;
        }

        setvalue = setvalue.substr(0, setvalue.length - 1);
        var where = " where " + key;
        where += "='";
        where += data[key] + "'";
        var sql = util.format("update %s %s %s", tablename, setvalue, where);
        var stmt = db_info.prepare(sql);
        stmt.run(value, function (error) {
            if (error) {
                console.log(error);
                console.log("and update the sql is :%s", sql);
                if (cb) {
                    cb(-1, error);
                }
                return;
            }
            else {
                stmt.finalize();
                if (cb != null)
                    cb(1, data[key]);
            }
        });
    });
}

//index 为唯一索引字段
//data为要插入或者更新的数据,和db_info_insert不同
//db_info_insert 根据所有预定义字段(db_define.js)插入，并更新所有字段
//db_info_insert_some自己写字段插入，只插入一些字段
//cb 为失败调用
function db_info_insert_some(tablename, index, data, cb) {
    //获取所有字段

    var fields = dbmap_cache(tablename, "fields");
    if (fields[index] == null) {
        console.log("error db_info_insert_some() key null");
        return;
    }
    var type = fields[index].type;
    console.log("type is " + type);
    if(judge_insert(type) == true ) //如果是可以插入的主键
    {
        if (data[index] == null) {
            console.log("db_info_insert_some(), index is null");
            return;
        }
        var sql = util.format("select count(*) as count from %s where %s ='%s' ", 
            tablename, index, data[index]);
        console.log(sql);
        db_info.get(sql, function (err, row) {
            if (err) {
                console.log("db_info_insert_some() error! the sql is %s", sql);
                return;
            }
            if(row.count > 0){
                var error = util.format("%s %s 数据不能重复", tablename, index);
                console.log(error);
                if (cb != null) {
                   cb(-1, error);
                }
            }
            else {
                db_info_insert_some2(tablename, data, cb);
            }
        });

    }else{
        db_info_insert_some2(tablename, data, cb);
    }
}

function db_info_insert_some2(tablename, data, cb) {
    //进行insert
    var fields = "";
    var para = "";
    //得到所有该表的列名
    var fields_ = dbmap_cache(tablename, "fields");
    if (fields_ == null || fields_.length == 0) {
        console.log("error,no %s fields", tablename);
        return;
    }
    var value = [];//插入的值
    //可以在全局定义里面查找是否有该字段，这里不查找
    for (var k in data) {
        if (fields_[k] != null) {//如果在数据表定义字段里面
            if (judge_insert(fields_[k].type) == true) { //如果是可以添加的字符串
                fields += k;
                fields += ","
                para += "?,";
                value.push(data[k]);
            }
        }
    }
    if (value.length == 0) {
        console.log("data is null");
        if (cb != null) {
            cb(-1, "no value,null");
        }
        return;
    }

    fields = fields.substr(0, fields.length - 1);
    para = para.substr(0, para.length - 1);
    var sql = util.format("insert into %s( %s ) values(%s)", tablename, fields, para);
    var stmt = db_info.prepare(sql);
    stmt.run(value, function (error) {
        if (error) {
            console.log("error sql :%s", sql);
            console.log(error);
            if (cb != null)
                cb(-1, error);
        }
        else {
            stmt.finalize();
            if (cb != null){
                var insertId = stmt.lastID;//获取自动生成的id
                cb(1, insertId);
            }
               
        }
        
    });
}


function obj_str_with_d(obj,flag){
    if(typeof(obj) != "object"){
        console.log(obj,"is not an object");
        return -1;
    }
    if (Array.prototype.isPrototypeOf(obj) == true) { //如果是数组
        console.log("is an array");
        return -1;
    }
    else{ //可能是对象
        var cc = 0;
        if(flag === 1){
            for (var k in obj) {
                cc++;
            }
            return cc;
        }
        else if (flag === 2) {
            var fields = "";
            for (var k in obj) {
                fields += k;fields += ","
            }
            fields = fields.substr(0, fields.length - 1);
            return fields;
        }
        else if (flag === 3) {
            var value = [];
            for (var k in obj) {
                value.push(obj[k]);
            }
            return value;
        }
        return -1;
    }
}


function get_params(fieldnum) {
    var para = "";
    for (var i = 0; i < fieldnum; i++) {
        if (i != fieldnum - 1)
            para += "?,";
        else
            para += "?";
    }
    return para;
}

//data2 是一个数组[{field:value,field:value},{field:value,field:value}]
function db_serialize(tablename, data, cb) {

    var isArray = false;
    //var isObject = true;
    if (typeof (data) != "object") {
        console.log("error not an object");
        return;
    }
    if (Array.prototype.isPrototypeOf(data) == true) { //如果又不是数组
        isArray = true;
    }

    db_info.serialize(function () {
        if (isArray) {
            for (var i = 0; i < data.length; i++) {
                var fieldnum = obj_str_with_d(data[i], 1); //计算个数
                var para = get_params(fieldnum);
                var fields = obj_str_with_d(data[i], 2);
                var sql = util.format("insert into %s( %s ) values(%s)", tablename, fields, para);
                var stmt = db_info.prepare(sql);
                var value = obj_str_with_d(data[i], 3);
                stmt.run(value, function (err) {
                    if (err) {
                        console.log(err, "the value is ", value);
                        if (cb != null) {
                            cb(-1, err);
                            return;
                        }
                    }
                });
                stmt.finalize();
            }
            if (cb != null)
                cb(1, data);
        }
        else {
            var fieldnum = obj_str_with_d(data, 1); //计算个数
            var para = get_params(fieldnum);
            var fields = obj_str_with_d(data, 2);
            var sql = util.format("insert into %s( %s ) values(%s)", tablename, fields, para);
            var stmt = db_info.prepare(sql);
            var value = obj_str_with_d(data, 3);
            stmt.run(value, function (err) {
                if (err) {
                    console.log(err, "the value is ", value);
                    if (cb != null) {
                        cb(-1, err);
                    }
                    else {
                        if (cb != null)
                            cb(1, data);
                    }
                }
            });
        }

    });
    return true;
}


function db_info_close() {
    console.log("closeDb");
    db_info.close();
}

function db_info_get() {
    return db_info;
}



exports.db_info_init2 = db_info_init2;
exports.db_info_get = db_info_get;
exports.db_info_insert = db_info_insert;
exports.db_info_update = db_info_update;
exports.db_info_update_some = db_info_update_some;
exports.db_info_delete = db_info_delete;
exports.db_info_delete_mul = db_info_delete_mul;
exports.db_info_delete_by_key = db_info_delete_by_key;
exports.db_info_read_count = db_info_read_count;
exports.db_info_read_page = db_info_read_page;
exports.db_info_read_page2 = db_info_read_page2;
exports.db_info_read_page3 =db_info_read_page3; 
exports.db_info_read_page4 = db_info_read_page4;
exports.db_info_close = db_info_close;
exports.db_info_select = db_info_select;
exports.db_info_select2 = db_info_select2;
exports.db_info_insert_some = db_info_insert_some;//_or_update = db_info_insert_or_update;
exports.db_info_insert_some2 = db_info_insert_some2;
exports.db_info_select_bysql = db_info_select_bysql;
exports.db_info_get_bysql = db_info_get_bysql;
exports.db_info_delete_bysql = db_info_delete_bysql;
exports.db_info_update_bysql = db_info_update_bysql;
// 数据库的操作:闵亚楠
exports.db_update_name = db_update_name;
exports.db_info_init3 = db_info_init3;
exports.db_edit_create_table = db_edit_create_table;
exports.db_edit_delete_table = db_edit_delete_table;
exports.db_edit_add_field = db_edit_add_field;
exports.db_info_select_mul = db_info_select_mul;
// exports.db_edit_delete_field = db_edit_delete_field;
exports.db_edit_get_tables = db_edit_get_tables;
exports.db_edit_get_fields = db_edit_get_fields;
exports.db_info_insert_norepeat = db_info_insert_norepeat;
//序列化输入，并非事务处理，可以一次输入多条数据
//data2 是一个数组[{field:value,field:value},{field:value,field:value}]
//function db_serialize(tablename, data, cb);
exports.db_serialize = db_serialize;